package com.webframe.web.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.mlw.vlh.ValueList;

import org.apache.commons.beanutils.BasicDynaBean;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.webframe.util.StringUtil;

@Controller
@RequestMapping("/extTree")
public class ExtTreeController extends BaseController {
	
	@Autowired
	private ValueListController valueListController;
	
	public String ClobToString(Clob clob) throws SQLException, IOException {

        String reString = "";
        Reader is = clob.getCharacterStream();// 得到流
        BufferedReader br = new BufferedReader(is);
        String s = br.readLine();
        StringBuffer sb = new StringBuffer();
        while (s != null) 
        {// 执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING
            sb.append(s);
            s = br.readLine();
        }
        reString = sb.toString();
        return reString;
    }
	/**
	 * @function 通过传入的adapter得到出树的json串,sql语句别名对应为树节点的属性
	 * @param request
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/queryNode")
	public String queryNode(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String key = request.getParameter("key");
		ValueList list = valueListController.getValueList(key, request);
		//拼json
		StringBuffer sb = new StringBuffer();
		BasicDynaBean dynaBean = null;
		DynaProperty [] dynaProperties;
		sb.append("[");
		for (Iterator iterator = list.getList().iterator(); iterator.hasNext();) {
			dynaBean = (BasicDynaBean) iterator.next();
			dynaProperties=dynaBean.getDynaClass().getDynaProperties();
			sb.append("{");
			for (int i = 0,length = dynaProperties.length; i < length; i++) 
			{
				sb.append(dynaProperties[i].getName());
				sb.append(":");
				Object value_ = dynaBean.get(dynaProperties[i].getName());
				if("true".equals(value_)||"false".equals(value_))
				{
					sb.append(value_);
				}
				else if (value_ instanceof Clob) 
				{
					String newValue = ClobToString((Clob)value_);
					sb.append("'"+StringUtil.replaceSpecilCharForJson(newValue)+"'");
				} 
				else
				{
					sb.append("'"+StringUtil.replaceSpecilCharForJson(value_)+"'");
				}
				if(i != dynaProperties.length-1)
				{
					sb.append(",");
				}
			}
			sb.append(",expanded:false");
			sb.append("}");
			if (iterator.hasNext()) {
				sb.append(",");
			}
		}
		sb.append("]");
		outWrite(response, sb.toString().replaceAll("\r\n",""));
		return null;
	}
	@SuppressWarnings("rawtypes")
	@RequestMapping("/queryAllChildNodes")
	public String queryAllChildNodes(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String id = request.getParameter("id");
		String key = request.getParameter("key");//查询所有指标分类ID
		StringBuffer sb = new StringBuffer();
		ValueList allIdList = valueListController.getValueList(key, request);
		BasicDynaBean dynaBean = null;
		if("-1".equals(id))
		{
			for (Iterator iterator = allIdList.getList().iterator(); iterator.hasNext();) {
				dynaBean = (BasicDynaBean) iterator.next();
				sb.append("'"+dynaBean.get("id_")+"'");
				if (iterator.hasNext()) 
				{
					sb.append(",");
				}
			}
		}
		else
		{
			sb.append("'"+id+"'");
			sb = queryById(id,allIdList,sb);
		}
		outWrite(response, sb.toString());
		return null;
		
	}
	/**
	 * 根据pid 查询当前节点的子节点
	 * @param id
	 * @param valueList
	 * @param sb
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public StringBuffer queryById(String id,ValueList valueList,StringBuffer sb)
	{
		StringBuffer sbTemp = new StringBuffer(); 
		BasicDynaBean dynaBean = null;
		for (Iterator iterator = valueList.getList().iterator(); iterator.hasNext();) 
		{
			dynaBean = (BasicDynaBean)iterator.next();
			if(id.equals(dynaBean.get("parentid_")))
			{
				sbTemp.append(",'"+dynaBean.get("id_")+"'");
			}
		}
		sb.append(sbTemp);
		if(StringUtils.isNotEmpty(sbTemp.toString()))
		{
			String[] str = sbTemp.toString().replaceAll("'", "").split(",");
			for (int i = 0,length = str.length; i < length; i++) 
			{
				queryById(str[i], valueList, sb);
			}
		}
		return sb;
	}
	
	/**
	 * 根据pid查询所有子节点
	 * @param id
	 * @param valueList
	 * @param sb
	 * @param request
	 * @param key
	 * @return
	 */
	@SuppressWarnings({
				"rawtypes", "unchecked"})
	public StringBuffer queryByIdAll(String id,ValueList valueList,StringBuffer sb,HttpServletRequest request,String key)
	{
		StringBuffer sbTemp = new StringBuffer(); 
		BasicDynaBean dynaBean = null;
		for (Iterator iterator = valueList.getList().iterator(); iterator.hasNext();) 
		{
			dynaBean = (BasicDynaBean)iterator.next();
			if(id.equals(dynaBean.get("parentid_")))
			{
				sbTemp.append(",'"+dynaBean.get("id_")+"'");
			}
		}
		sb.append(sbTemp);
		if(StringUtils.isNotEmpty(sbTemp.toString()))
		{
			String[] str = sbTemp.toString().replaceAll("'", "").split(",");
			for (int i = 0,length = str.length; i < length; i++) 
			{
				Map ids = new HashMap();
				ids.put("id", str[i]);
				ValueList allIdList = valueListController.getValueList(key, request,ids);
				queryById(str[i],allIdList,sb);
			}
		}
		return sb;
	}
}